package com.cet.algorithm.字符串;

/**
 * @program: algorithm
 * @description: 字符串左旋
 * @author: 陈恩涛
 * @create: 2022-03-21 17:48
 **/
public class JZOffer58 {

    public static String reverseLeftWords(String s, int n) {
        String leftString = s.substring(0, n);
        String rightString = s.substring(n);
        return rightString + leftString;
    }

    /**
     * 加大难度，不申请额外的空间
     * 反转区间为前n的子串
     * 反转区间为n到末尾的子串
     * 反转整个字符串
     * @param s
     * @param n
     * @return
     */
    public static String reverseLeftWords2(String s, int n) {
        StringBuilder result = new StringBuilder(s);
        reverseString(result, 0, n - 1);
        reverseString(result, n, s.length() - 1);
        reverseString(result, 0, s.length() - 1);
        return result.toString();
    }

    /**
     * 反转字符串中从start到end的子串
     * @param sb
     * @param start
     * @param end
     */
    public static void reverseString(StringBuilder sb, int start, int end) {
        while (start < end) {
            char temp = sb.charAt(start);
            sb.setCharAt(start, sb.charAt(end));
            sb.setCharAt(end, temp);
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        System.out.println(reverseLeftWords2("abcdddddss", 2));
    }
}
